package com.xiong.springsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiong.springsecurity.domain.User;
import com.xiong.springsecurity.mapper.MenuMapper;
import com.xiong.springsecurity.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *
 * @author XiongDa
 * @version 1.0.0
 * @belongsProject: SpringSecurity
 * @belongsPackage: com.xiong.springsecurity.service.impl
 * @since 2023/6/14 10:53
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    private final PasswordEncoder passwordEncoder;

    private final MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        // 1. 通过用户名查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserName, userName));
        if (Objects.isNull(user)){
            throw new RuntimeException("用户名不存在");
        }

        // 2. 查询权限信息, 添加到 LoginUser
        List<String> strings = menuMapper.selectPermsByUserId(user.getId());
        log.info("用户的权限信息: {}", strings);
//        List<String> authorities =  new ArrayList<>(Arrays.asList("test", "admin"));

        return new LoginUser(user, strings);
    }
}
